/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.diplomka.webapp.alliance;

import cz.muni.fi.diplomka.servicelayer.dto.Alliance;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.AlliancesManager;
import cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl.AlliancesManagerImpl;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;

/**
 *
 * @author Jakub Kutil
 */
public class CreatePanel extends Panel {

    private AlliancesManager alliancesManager = new AlliancesManagerImpl();

    public CreatePanel(String id, PageParameters parameters) {
        super(id);

        if (parameters.containsKey("id")) {
            final Long playerId = parameters.getLong("id");

            final TextField<String> name = new TextField<>("name",
                    Model.of(""));

            Form<?> createAlliance = new Form<Void>("createAlliance") {
                @Override
                protected void onSubmit() {
                    if (alliancesManager.getAllianceByName(name.getValue()).getId() == null) {
                        Alliance alliance = new Alliance();
                        alliance.setName(name.getValue());
                        
                        alliancesManager.createAlliance(alliance);
                        
                        alliancesManager.joinAlliance(playerId, alliancesManager.getAllianceByName(name.getValue()).getId());
                        
                        PageParameters pageParameters = new PageParameters();
                        pageParameters.add("id", playerId.toString());
                        setResponsePage(AlliancePage.class, pageParameters);
                    } else {
                        error("Name already taken");
                    }
                }
            };

            add(createAlliance);
            createAlliance.add(name);
        }
    }
}